import { defineStore } from "pinia";
import {
  addData,
  editData,
  deleteData,
  getTableBody,
  getSelectList,
  getProvList,
} from "@/services/userManage.service";
import { message, Modal } from "ant-design-vue";
import { cloneDeep } from "lodash";
import { getQueryStringData } from "@/utils/tool.js";
import moment from "moment";
export const userManage = defineStore("user-manage", {
  state: () => {
    return {
      searchData: {
        username: "",
        realname: "",
        phone: "",
        selecteddeparts: null,
        status: null,
      },
      searchList: [
        {
          view: "text",
          key: "username",
          title: "用户账号",
        },
        {
          view: "text",
          key: "realname",
          title: "用户名称",
        },
        {
          view: "text_number",
          key: "phone",
          title: "手机号码",
        },
        {
          view: "cat_tree",
          key: "selecteddeparts",
          title: "数据权限",
        },
        {
          view: "radio",
          key: "status",
          title: "用户状态",
        },
      ], //查询条件
      formKey: [
        {
          view: "text",
          key: "username",
          title: "用户账号",
        },
        {
          view: "passWord",
          key: "password",
          title: "登录密码",
        },
        {
          view: "passWord",
          key: "confirmPassword",
          title: "确认密码",
        },
        {
          view: "text",
          key: "realname",
          title: "用户名称",
        },
        {
          view: "text_number",
          key: "phone",
          title: "手机号码",
        },
        {
          view: "cat_tree",
          key: "selecteddeparts",
          title: "数据权限",
        },
        {
          view: "sel_search",
          key: "selectedroles",
          title: "用户角色",
        },
        {
          view: "radio",
          key: "status",
          title: "用户状态",
        },
      ], //表单item
      formData: {}, //表单回显
      columns: [
        {
          title: "用户账号",
          dataIndex: "username",
          align: "center",
          fixed: "left",
          ellipsis: true,
          width: 200,
        },
        {
          title: "用户名称",
          dataIndex: "realname",
          align: "center",
          ellipsis: true,
        },
        {
          title: "用户角色",
          dataIndex: "selectedroles",
          align: "center",
          ellipsis: true,
          scopedSlots: { customRender: "selectedroles" },
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          align: "center",
          ellipsis: true,
          width: 120,
        },
        {
          title: "数据权限",
          dataIndex: "orgCodeTxt",
          align: "center",
          ellipsis: true,
        },
        {
          title: "状态",
          dataIndex: "status",
          align: "center",
          ellipsis: true,
          scopedSlots: { customRender: "status" },
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          align: "center",
          ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "operate",
          align: "center",
          fixed: "right",
          scopedSlots: { customRender: "operate" },
        },
      ],
      tableData: [],
      option: [],
      deleteId: [], //批量删除选中项
      id: getQueryStringData("id"),
      userId: decodeURIComponent(getQueryStringData("userId")),
      pageNo: 1,
      pageSize: 15,
      total: 0,
      dimCode: "",
      visible: false,
      visiblePreview: false,
      disable: false,
      title: "查看-维度管理单",
      tableName: "sys_user",
      editNameBack: "", //编辑备份名称
      treeData: [], //省分地市树结构
    };
  },
  getters: {},
  actions: {
    async reSet() {
      this.searchData = {
        username: "",
        realname: "",
        phone: "",
        selecteddeparts: null,
        status: null,
      };
      if (this.pageNo === 1) {
        await this.getTbodyData();
      } else {
        this.pageNo = 1;
      }
    },
    async getRegion(params) {
      const res = await getProvList();
      if (res && (res.code === 200 || res.code === 0)) {
        this.treeData = res.result;
      } else {
        this.treeData = [];
      }
    },
    //新增保存
    async addDataObj() {
      const res = await addData({
        ...this.formData,
        selecteddeparts: this.formData.selecteddeparts[0].value,
        selectedroles: this.formData.selectedroles,
      });
      if (res.code === 200) {
        message.success(res.message, 2);
      } else {
        message.error((res && res?.message) || "新增失败", 2);
      }
      return (res && res?.code) || 400;
    },
    //编辑报存
    async editDataObj() {
      const res = await editData({
        ...this.formData,
        selecteddeparts: this.formData.selecteddeparts[0].value,
        selectedroles: this.formData.selectedroles,
      });
      if (res.code === 200) {
        message.success(res.result, 2);
      } else {
        message.error((res && res?.result) || "编辑失败", 2);
      }
      return (res && res?.code) || 400;
    },
    async submit() {
      if (this.title.includes("修改")) {
        await this.editDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData();
          }
        });
      } else {
        await this.addDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData();
          }
        });
      }
    },
    //新增操作
    addDataOperation(title) {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else if (item.view === "cat_tree" || item.view === "radio") {
          obj[item.key] = null;
        } else {
          obj[item.key] = "";
        }
      });
      if ("editor" in obj) {
        obj["editor"] = this.userId;
      }
      if ("update_time" in obj) {
        obj["update_time"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }
      this.formData = { ...obj };
      this.visible = true;
      this.disable = false;
      this.title = title;
    },
    offModal() {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else if (item.view === "date") {
          obj[item.key] = null;
        } else if (item.view === "cat_tree" || item.view === "cat_tree_auth") {
          obj[item.key] = null;
        } else {
          obj[item.key] = "";
        }
      });
      this.formData = { ...obj };
      this.visible = false;
    },
    findTitleObj(title, arr) {
      for (let item of arr) {
        if (item.title === title) {
          return [{ label: item.title, value: item.key }];
        }
        if (item.children) {
          let result = this.findTitleObj(title, item.children);
          if (result.length > 0) {
            return result;
          }
        }
      }
      return [];
    },
    //编辑操作
    async editDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);
      console.log(obj, "obj");
      if ("editor" in obj && status) {
        obj["editor"] = this.userId;
      }
      if ("update_time" in obj) {
        obj["update_time"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }
      let selecteddeparts = [];
      if ("orgCodeTxt" in obj) {
        selecteddeparts = this.findTitleObj(obj["orgCodeTxt"], this.treeData);
      }
      this.formData = { ...obj, selecteddeparts };
      this.visible = true;
      if (type) {
        this.disable = true;
      } else {
        this.disable = false;
      }
      this.editNameBack = record[this.formKey[0].key];
      this.title = title;
    },
    async previewDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);
      let selecteddeparts = [];
      if ("orgCodeTxt" in obj) {
        selecteddeparts = this.findTitleObj(obj["orgCodeTxt"], this.treeData);
      }
      this.formData = { ...obj, selecteddeparts };
      this.visiblePreview = true;
      if (type) {
        this.disable = true;
      } else {
        this.disable = false;
      }
      this.editNameBack = record[this.formKey[0].key];
      this.title = title;
    },
    //删除
    async deleteDataObj(record, type) {
      let that = this;
      if (!type && this.deleteId.length === 0) {
        return Modal.info({
          title: "提示",
          content: "至少选择一条数据",
          centered: true,
        });
      }
      if (record.username === "admin") {
        return Modal.info({
          title: "提示",
          content: "管理员您好，admin账号是唯一的超级管理员，暂时不可删除",
          centered: true,
        });
      }
      Modal.confirm({
        title: "提示",
        content: "确定删除选中数据吗",
        okText: "确定",
        cancelText: "取消",
        centered: true,
        onOk() {
          return new Promise((resolve, reject) => {
            deleteData({
              id: type ? "delete" : "deleteBatch",
              deleteId: type ? record.id : that.deleteId.join(","),
            }).then((res) => {
              if (res.code === 200) {
                //关闭弹窗
                resolve();
                that.getTbodyData();
                message.success(res.result, 2);
              } else {
                //不关闭弹窗
                reject();
                message.error(res.result || "指标分类删除失败", 2);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    async getTbodyData() {
      let params = cloneDeep(this.searchData);
      for (let key in params) {
        if (!params[key] || params[key].length === 0) {
          delete params[key];
        } else {
          if (key === "selecteddeparts") {
            params[key] = params[key][0].value;
          } else if (key.includes("name")) {
            params[key] = "*" + params[key] + "*";
          } else if (key === "phone") {
            params[key] = "*" + params[key] + "*";
          }
        }
      }
      const res = await getTableBody({
        column: "createTime",
        order: "desc",
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...params,
      });
      if (res.code === 0) {
        this.total = res.result.total !== 0 ? res.result.total - 2 : 0;
        this.tableData =
          res.result?.records?.filter(
            (item) =>
              item.username !== "jeecg_admin" && item.username !== "test_admin"
          ) || [];
      } else {
        this.total = 0;
        this.tableData = [];
      }
    },
    //查询
    async search() {
      this.deleteId = [];
      if (this.pageNo === 1) {
        await this.getTbodyData();
      } else {
        this.pageNo = 1;
      }
      await this.getSelectData();
    },
    updateSearchData(key, value) {
      this.searchData[key] = value;
      this.searchData = { ...this.searchData };
    },
    updateFormData(key, value) {
      this.formData[key] = value;
      this.formData = { ...this.formData };
    },
    updateDeleteId(selectArr) {
      this.deleteId = selectArr;
    },
    async getSelectData() {
      const res = await getSelectList();
      if (res.code === 200 || res.code === 0) {
        this.option = res.result.filter(
          (item) => item.roleCode !== "jeecg_admin"
        );
      } else {
        this.option = [];
      }
    },
  },
});
